package com.test.com.bluetoothchatandroid.thread;

import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;

import com.orhanobut.logger.Logger;
import com.test.com.bluetoothchatandroid.global.BluetoothState;
import com.test.com.bluetoothchatandroid.global.ChatConstant;
import com.test.com.bluetoothchatandroid.utils.BluetoothChatHelper;

import java.io.IOException;

/**
 * Created by ${cs} on 2018/4/20.
 * @author saviorT
 * 监听线程
 */

public class AcceptThread extends Thread {

	private BluetoothChatHelper mHelper;
	private final BluetoothServerSocket mServerSocket;
	private String mSocketType;

	public AcceptThread(BluetoothChatHelper bluetoothChatHelper, boolean secure) {
		mHelper = bluetoothChatHelper;
		BluetoothServerSocket serverSocket = null;
		mSocketType = secure?"Secure":"Insecure";

		try{
			if (secure) {
			serverSocket = mHelper.getAdapter().listenUsingRfcommWithServiceRecord(ChatConstant.NAME_SECURE, ChatConstant.UUID_SECURE);
		} else {
			serverSocket = mHelper.getAdapter().listenUsingInsecureRfcommWithServiceRecord(ChatConstant.NAME_INSECURE, ChatConstant.UUID_INSECURE);
		}
		}catch (IOException e){
			Logger.d("获取套接字失败"+e.getMessage());
		}
		mServerSocket = serverSocket;

	}

	@Override
	public void run() {
		setName("AcceptThread "+mSocketType);

		BluetoothSocket socket = null;
		while (mHelper.getState() != BluetoothState.STATE_CONNECTED){
			try{
				socket = mServerSocket.accept();
			}catch (IOException e){
				break;
			}

			if (socket != null){
				synchronized (this){
					if (mHelper.getState() == BluetoothState.STATE_LISTEN
							|| mHelper.getState() == BluetoothState.STATE_CONNECTING){
						Logger.d("正在连接.....");
						mHelper.connected(socket,socket.getRemoteDevice(),mSocketType);
					}else if (mHelper.getState() == BluetoothState.STATE_NONE
							|| mHelper.getState() == BluetoothState.STATE_CONNECTED){
						try{
							socket.close();
						}catch (IOException e){
							Logger.d("套接字关闭异常.");
						}
					}
				}
			}
		}

		Logger.d("线程类型 "+mSocketType+"AcceptThread 线程结束");
	}

	public void cancel() {
		Logger.d(mSocketType+"套接字 取消");
		try {
			mServerSocket.close();
		} catch (IOException e) {
			Logger.d("mServerSocket 关闭出错");
		}
	}
}
